package com.angel.kuaidi.service;

import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import com.angel.kuaidi.R;
import com.angel.kuaidi.KuaidiConstans;
import com.angel.kuaidi.utils.Utils;

import android.app.Activity;
import android.app.AlertDialog;
import android.app.Notification;
import android.app.NotificationManager;
import android.app.PendingIntent;
import android.app.ProgressDialog;
import android.app.Service;
import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager.NameNotFoundException;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.net.Uri;
import android.os.Handler;
import android.os.IBinder;
import android.os.Looper;
import android.os.Message;
import android.widget.Button;
import android.widget.ProgressBar;
import android.widget.RemoteViews;
import android.widget.TextView;

/**
 * 更新APK的类
 * 
 * @author hongyun.fang
 * @version 1.6.0 1.Set apkUrl 2.check() 3.add delFile() method in resume()\onPause()
 */
public class UpdateAPKService extends Service {

	/** 是否要显示安装提示页面 */
	public boolean isShowInstall;

	/** 上下文对象 */
	public Context context;
	/** 新apk的网络url */
	public String strURL;

	/** apk包的缓存路径 */
	public String cacheFilePath;
	/** apk文件名 */
	public String apkFileName = "";
	/** 下载apk包的临时路径 */
	private String currentTempFilePath = "";

	public int versionCode = 0;
	public String versionName = "";
	private ProgressDialog dialog;
	Button tv;
	long length;
	long totalLength;

	//
	private NotificationManager nm;
	private Notification notification;
	private RemoteViews views;
	private int notificationId = 0x123450;

	private MyHandler handler;

	@Override
	public void onCreate() {
		// TODO Auto-generated method stub
		super.onCreate();
		this.context = this;
		cacheFilePath = Utils.getRootPath(KuaidiConstans.ROOT_CACHE_DIR_PATH);
	}

	@Override
	public void onStart(Intent intent, int startId) {
		super.onStart(intent, startId);

		this.strURL = intent.getStringExtra("url");
		handler = new MyHandler(Looper.myLooper());
		start();
	}

	class MyHandler extends Handler {

		public MyHandler(Looper looper) {
			super(looper);
		}

		@Override
		public void handleMessage(Message msg) {
			if (msg.what == 1) {
				views.setTextViewText(R.id.tv_Process,
						"已下载" + (length * 100 / totalLength) + "%  " + String.format("%1$04.2f", length / 1024F) + "KB/" + String.format("%1$04.2f", totalLength / 1024F) + "KB");
				views.setProgressBar(R.id.pb_Download, 100, (int) (length * 100 / totalLength), false);
				notification.contentView = views;
				notification.flags = Notification.FLAG_AUTO_CANCEL;
				nm.notify(notificationId, notification);
			} else if (msg.what == 2) {// 错误
				views.setTextViewText(R.id.tv_Process, "更新下载失败!");
				views.setProgressBar(R.id.pb_Download, 100, (int) (length * 100 / totalLength), false);
				notification.contentView = views;
				notification.flags = Notification.FLAG_AUTO_CANCEL;
				nm.notify(notificationId, notification);
				stopSelf();
			} else if (msg.what == 3) {
				// 下载完成
				views.setTextViewText(R.id.tv_Process, "下载完成");
				views.setProgressBar(R.id.pb_Download, 100, 100, false);
				notification.contentView = views;
				notification.flags = Notification.FLAG_AUTO_CANCEL;
				nm.notify(notificationId, notification);
				nm.cancel(notificationId);
				// 跳转到安装页面
				openFile((File) msg.obj);
			}
		}
	};

	/**
	 * 检验网络，并进行更新apk的处理的调用
	 */
	public void start() {
		initView();
		//
		downloadTheFile(strURL);
	}

	private void initView() {

		nm = (NotificationManager) context.getSystemService(Context.NOTIFICATION_SERVICE);
		notification = new Notification();
		notification.icon = R.drawable.ic_icon;
		// notification.icon=android.R.drawable.stat_sys_download_done;
		notification.tickerText = context.getString(R.string.app_name) + "更新";
		notification.when = System.currentTimeMillis();
		notification.defaults = Notification.DEFAULT_LIGHTS;
		// 设置任务栏中下载进程显示的views
		views = new RemoteViews(context.getPackageName(), R.layout.update);
		notification.contentView = views;

		// 传递一个空的intent
		PendingIntent contentIntent = PendingIntent.getActivity(context, 0, new Intent(), 0);
		notification.contentIntent = contentIntent;
		// notification.setLatestEventInfo(context, "", "", contentIntent);
		// 将下载任务添加到任务栏中
		nm.notify(notificationId, notification);

	}

	/**
	 * 下载apk文件的预处理方法
	 * 
	 * @param strPath
	 *            新apk的网络url
	 */
	private void downloadTheFile(final String strPath) {
		apkFileName = strPath.substring(strPath.lastIndexOf("/") + 1, strPath.length());
		new Thread(new Runnable() {
			@Override
			public void run() {
				try {
					// 下载前先清空垃圾文件
					File file = new File(cacheFilePath);
					File[] files = file.listFiles();
					if (files != null) {
						for (File f : files) {

							if (f.exists()) {
								f.delete();
							}
						}
					}

					// 下载apk文件
					doDownloadTheFile(strPath);
				} catch (Exception e) {
					e.printStackTrace();
					handler.sendMessage(handler.obtainMessage(2));
				}
			}
		}).start();
	}

	/**
	 * 下载apk文件
	 * 
	 * @param strPath
	 *            新apk的网络url
	 * @throws Exception
	 *             异常对象
	 */
	private void doDownloadTheFile(String strPath) throws Exception {
		// 判断strPath是否是一个可用的网络URL

		URL myURL = new URL(strPath);
		URLConnection conn = myURL.openConnection();
		conn.connect();
		InputStream is = conn.getInputStream();
		totalLength = conn.getContentLength();

		if (is == null) {
			throw new RuntimeException("stream is null");
		}

		File path = new File(cacheFilePath);
		if (!path.exists()) {
			path.mkdirs();
		}

		File myTempFile = new File(cacheFilePath + apkFileName);
		currentTempFilePath = myTempFile.getAbsolutePath();
		BufferedOutputStream bos = new BufferedOutputStream(new FileOutputStream(myTempFile));
		byte buf[] = new byte[512];
		long old = 0;
		do {
			int numread = is.read(buf);
			if (numread <= 0) {
				break;
			}
			bos.write(buf, 0, numread);
			length += numread;
			// 更新页面
			if ((((length - old) * 100.0f) / totalLength) > 3.8) {
				old = length;
				handler.sendMessage(handler.obtainMessage(1));
			}
		} while (true);

		bos.flush();
		bos.close();
		handler.sendMessage(handler.obtainMessage(1));
		// 通知下载完成
		Message msg = handler.obtainMessage(3);
		msg.obj = myTempFile;
		handler.sendMessage(msg);

		try {
			is.close();

		} catch (Exception ex) {
			ex.printStackTrace();
			handler.sendMessage(handler.obtainMessage(2));
		}
	}

	public static boolean isNetworkAvailable(Context ctx) {
		try {
			ConnectivityManager cm = (ConnectivityManager) ctx.getSystemService(Context.CONNECTIVITY_SERVICE);
			NetworkInfo info = cm.getActiveNetworkInfo();
			return (info != null && info.isConnected());
		} catch (Exception e) {
			e.printStackTrace();
			return false;
		}
	}

	private void openFile(File f) {
		Intent intent = new Intent();
		intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
		intent.setAction(android.content.Intent.ACTION_VIEW);
		String type = getMIMEType(f);
		intent.setDataAndType(Uri.fromFile(f), type);
		context.startActivity(intent);
		stopSelf();
	}

	public void delFile() {
		File myFile = new File(currentTempFilePath);
		if (myFile.exists()) {
			myFile.delete();
		}
	}

	private String getMIMEType(File f) {
		return "application/vnd.android.package-archive";
	}

	@Override
	public IBinder onBind(Intent arg0) {
		// TODO Auto-generated method stub
		return null;
	}
}